<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-row>
        <el-col :span="4.2">
          <el-form-item label="病案号" prop="medicareNo" label-width="70px">
            <el-input
              v-model="queryParams.medicareNo"
              placeholder="请输入病案号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4.2">
          <el-form-item label="患者姓名" prop="patientName">
            <el-input
              v-model="queryParams.patientName"
              placeholder="请输入患者姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="4.1">
          <el-form-item label="监护分级" prop="guardianLevel">
            <el-select
              v-model="queryParams.guardianLevel"
              placeholder="请选择监护分级"
              clearable
            >
              <el-option
                v-for="(item, index) in guardianLevel"
                :key="index"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.1">
          <el-form-item label="完成状态" prop="summaryState">
            <el-select
              v-model="queryParams.summaryState"
              placeholder="请选择完成状态"
              clearable
            >
              <el-option label="已完成" :value="1"></el-option>
              <el-option label="未完成" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4.3">
          <el-form-item label="出院时间">
            <el-date-picker
              v-model="time"
              type="daterange"
              range-separator="至"
              start-placeholder="请选择开始日期"
              end-placeholder="请选择结束日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              @change="handletime"
              clearable
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        style="display: flex; justify-content: flex-end; padding-right: 28px"
      >
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索
          </el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
          </el-button
          >
        </el-form-item>
      </el-row>
    </el-form>
    <el-table
      v-loading="loading"
      :data="baseInfoList"
      border=""
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" type="index" align="center" width="50">
      </el-table-column>
      <el-table-column label="病案号" align="center" prop="medicareNo"/>
      <el-table-column label="患者姓名" align="center" prop="patientName"/>
      <el-table-column label="第一诊断" align="center" prop="firstDiagnose"/>
      <el-table-column
        label="入院时间"
        align="center"
        prop="admissionTime"
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="出院时间"
        align="center"
        prop="dischargeTime"
        width="180"
      >
      </el-table-column>
      <el-table-column label="住院天数" align="center" prop="inDays"/>
      <el-table-column label="完成状态" align="center" prop="summaryState">
        <template slot-scope="scope">
          <el-tag :type="scope.row.summaryState == 1 ? 'success' : 'danger'">
            {{ scope.row.summaryState == 1 ? '已完成' : '未完成' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleLook(scope.row)"
          >查看
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            :loading="downAllyaoLiXiaoLoading"
            @click="downyaoLi(scope.row)"
          >下载
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-hasPermi="['workstation:statistics:my:remove']"
            @click="handleDelete(scope.row)"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改患者基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="85px"
        label-position="left"
      >
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名"/>
        </el-form-item>
        <el-form-item label="ID号" prop="patientNo">
          <el-input v-model="form.patientNo" placeholder="请输入ID号"/>
        </el-form-item>
        <el-form-item label="科室/病区" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择科室/病区"
          />
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker
            clearable
            v-model="form.admissionTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择入院时间"
            :picker-options="setDisabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="住院医师" prop="doctorId">
          <el-select
            v-model="form.doctorId"
            placeholder="请选择临床药师"
            clearable
            @change="handleDoctorName"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in DoctorList"
              :key="index"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="床号" prop="bedNo">
          <el-input v-model="form.bedNo" placeholder="请输入床号"/>
        </el-form-item>
        <el-form-item label="第一诊断" prop="firstDiagnose">
          <el-input v-model="form.firstDiagnose" placeholder="请输入第一诊断"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
        >确 定
        </el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mylist, remove } from '@/api/tongjiguanli/index.js'
import {
  listBaseInfo,
  getBaseInfo,
  delBaseInfo,
  addBaseInfo,
  updateBaseInfo
} from '@/api/workstation/baseInfo'
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
  deptList
} from '@/api/system/user'
import { getDicts } from '@/api/system/dict/data'

export default {
  name: 'myYaoLi',
  data() {
    return {
      downAllyaoLiXiaoLoading: false, // 下载按钮加载状态
      setDisabled: {
        // 返回禁用时间
        disabledDate(time) {
          return time.getTime() > Date.now() // 可选历史天、可选当前天、不可选未来天
          // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
          // return time.getTime() < Date.now() - 8.64e7;  // 不可选历史天、可选当前天、可选未来天
          // return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
        }
      },
      // 部门树选项
      deptOptions: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者基本信息表格数据
      baseInfoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorName: undefined, // 住院医师的名字  搜索
        medicareNo: undefined,
        patientName: undefined,
        // medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        // admissionDate: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        nickName: undefined, // 昵称
        dischargeTime: undefined, // 出院时间
        summaryState: undefined // 完成状态
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: '患者ID不能为空', trigger: 'blur' }],
        patientName: [
          { required: true, message: '患者姓名不能为空', trigger: 'blur' }
        ],
        medicalRecordNo: [
          { required: true, message: '病案号不能为空', trigger: 'blur' }
        ],
        patientNo: [
          { required: true, message: 'ID号不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '科室/病区不能为空', trigger: 'blur' }
        ],
        admissionTime: [
          { required: true, message: '入院时间不能为空', trigger: 'blur' }
        ],
        doctorId: [
          { required: true, message: '临床药师不能为空', trigger: 'blur' }
        ],
        bedNo: [{ required: true, message: '床号不能为空', trigger: 'blur' }],
        firstDiagnose: [
          { required: true, message: '第一诊断不能为空', trigger: 'blur' }
        ],
        guardianLevel: [
          { required: true, message: '监护分级不能为空', trigger: 'blur' }
        ],
        patientState: [
          { required: true, message: '住院状态不能为空', trigger: 'blur' }
        ],
        patientSex: [
          { required: true, message: '患者性别不能为空', trigger: 'change' }
        ],
        patientAge: [
          { required: true, message: '年龄不能为空', trigger: 'blur' }
        ],
        patientProfession: [
          { required: true, message: '职业不能为空', trigger: 'blur' }
        ],
        nation: [{ required: true, message: '民族不能为空', trigger: 'blur' }],
        patientHeight: [
          { required: true, message: '身高不能为空', trigger: 'blur' }
        ],
        patientWeight: [
          { required: true, message: '体重不能为空', trigger: 'blur' }
        ],
        patientBmi: [
          { required: true, message: 'BMI不能为空', trigger: 'blur' }
        ],
        phoneNo: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' }
        ],
        payWay: [
          { required: true, message: '付费方式不能为空', trigger: 'blur' }
        ],
        sourceInfo: [
          { required: true, message: '数据来源不能为空', trigger: 'blur' }
        ]
      },
      guardianLevel: [], // 监护分级
      patientState: [], // 住院状态
      userSex: [], // 患者性别
      payWay: [], // 付费方式
      sourceInfo: [], // 患者信息来源
      DoctorList: [], // 对应科室的医生列表
      msg: {}, // 患者管理页搜索条件
      time: '' // 起始日期
    }
  },
  computed: {
    role() {
      return this.$store.state.user.roles
    },
    useInfo() {
      return this.$store.state.user.user
    },
    info() {
      return this.$store.state.user.search
    }
  },
  created() {
    this.queryParams.nickName = this.useInfo.nickName
    this.getList()
    // 字典查询  监护分级
    getDicts('guardian_level').then((res) => {
      this.guardianLevel = res.data
    })
    // 字典查询  住院状态
    getDicts('patient_state').then((res) => {
      this.patientState = res.data
    })
  },
  methods: {
    handletime(val) {
      if (val) {
        this.queryParams['params[beginDate]'] = val[0]
        this.queryParams['params[endDate]'] = val[1]
        console.log(this.queryParams)
      } else {
        this.queryParams['params[beginDate]'] = ''
        this.queryParams['params[endDate]'] = ''
      }
    },
    // 去患者详情页
    toUseDetail(item) {
      this.$store.commit('SET_SEARCH', this.queryParams)
      // 打开新窗口
      window.open(
        `/detail?id=${item.id}&medicalRecodeNo=${item.medicalRecordNo}`
      )
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      // 质控员 拥有所有科室
      if (this.role.includes('quality')) {
        deptTreeSelect().then((response) => {
          this.deptOptions = response.data
        })
        return
      }
      console.log('用户信息', this.useInfo)
      // 指定了常驻病区 下拉查询
      if (this.useInfo.longDept) {
        let params = {}
        params.params = {}
        params.params['longDept'] = this.useInfo.longDept
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = []
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId
            }
            arr.push(obj)
          })
          this.deptOptions = arr
        })
      } else {
        // 指定了科室  没有指定病区
        let params = {
          parentId: this.useInfo.deptId
        }
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = []
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId
            }
            arr.push(obj)
          })
          this.deptOptions = arr
        })
      }
    },
    /** 查询患者基本信息列表 */
    getList() {
      this.loading = true
      mylist(this.queryParams).then((response) => {
        this.baseInfoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        admissionDate: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        nickName: this.useInfo.nickName,
        'params[beginDate]': '',
        'params[endDate]': ''
      }
      this.time = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 查看按钮操作
    handleLook(row) {
      // 打开新窗口
      window.open(
        `/medicine?id=${row.id}&medicalRecordNo=${row.medicalRecordNo}`
      )
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加患者基本信息'
    },
    handleDoctorName(val) {
      let person = this.DoctorList.filter((item) => {
        return item.userId == val
      })
      this.form.doctorName = person[0].nickName
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 打开新窗口
      window.open(
        `/medicine?id=${row.id}&medicalRecordNo=${row.medicalRecordNo}`
      )
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          } else {
            this.form.sourceInfo = '0' // 代表是手工录入
            addBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row.medicalRecordNo)
      //   const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除 ' + row.patientName + ' 的数据项？')
        .then(() => {
          this.loading = true
          return remove(row.medicalRecordNo)
        })
        .then(() => {
          this.loading = false
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 下载药历
    downyaoLi(row) {
      this.downAllyaoLiXiaoLoading = true
      this.$download.get(
        '/workstation/medicationRecord/overall/',
        row.medicalRecordNo,
        `${row.patientName}.docx`
      )
      this.downAllyaoLiXiaoLoading = false
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'workstation/baseInfo/export',
        {
          ...this.queryParams
        },
        `baseInfo_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-form-item--small.el-form-item {
  margin: 0 !important;
  margin-bottom: 10px !important;
}
</style>
